<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单名称" prop="psorderNo">
        <el-input v-model="queryParams.psorderNo" placeholder="请输入订单名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="旺旺名" prop="wangName">
        <el-input v-model="queryParams.wangName" placeholder="请输入旺旺名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="店铺号" prop="storeName">
        <!-- <el-input v-model="queryParams.storeName" placeholder="请输入店铺号" clearable @keyup.enter.native="handleQuery" /> -->
        <el-select v-model="queryParams.storeName" placeholder="请输入店铺名称" clearable>
            <el-option
              v-for="dict in dict.type.store"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="订单价格" prop="psorderAmount">
        <el-input v-model="queryParams.psorderAmount" placeholder="请输入订单价格" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="psorderState">
        <el-select v-model="queryParams.psorderState" placeholder="请选择订单状态" clearable>
          <el-option v-for="dict in psorderStateOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="抢单类型" prop="psorderSort">
        <el-select v-model="queryParams.psorderSort" placeholder="请选择抢单类型" clearable>
          <el-option v-for="dict in psorderSortOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建者" prop="createBy">
        <el-input v-model="queryParams.createBy" placeholder="请输入创建者" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['dashboard:psorders:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['dashboard:psorders:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['dashboard:psorders:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['dashboard:psorders:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="psordersList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="PS订单ID" align="center" prop="id" /> -->
      <el-table-column label="订单名称" align="center" prop="psorderNo" />
      <el-table-column label="旺旺名" align="center" prop="wangName" />
      <el-table-column label="店铺号" align="center" prop="storeName" />

      <el-table-column label="订单图片" align="center" prop="psorderPicture">
        <template slot-scope="scope">
          <div v-if="scope.row.psorderPicture">
            <img v-for="(imgUrl, index) in scope.row.psorderPicture.split(',')" :key="index" :src="imgUrl"
              style="width: 50px; height: 50px; margin-right: 5px; object-fit: cover;" />
          </div>
          <span v-else>无图片</span>
        </template>
      </el-table-column>

      <el-table-column label="订单价格" align="center" prop="psorderAmount" />
      <el-table-column label="订单状态" align="center" prop="psorderState">
        <template slot-scope="scope">
          <el-select v-model="scope.row.psorderState" @change="(val) => handleOrderStatusChange(val, scope.row)"
            size="mini">
            <el-option v-for="dict in psorderStateOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="抢单类型" align="center" prop="psorderSort">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(psorderSortOptions, scope.row.psorderSort) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="抢单人" align="center" prop="acceptedProgrammerId">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(programmerOriginalUserOptions, scope.row.acceptedProgrammerId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建者" align="center" prop="createBy" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['dashboard:psorders:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['dashboard:psorders:remove']">删除</el-button>
          <el-button v-if="scope.row.psorderState === '3' && scope.row.psorderSort === '1'" size="mini" type="text"
            icon="el-icon-s-finance" @click="handleWithdrawalApply(scope.row)"
            v-hasPermi="['dashboard:psorders:query']">提现申请</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改PS订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="订单名称" prop="psorderNo">
          <el-input v-model="form.psorderNo" placeholder="请输入订单名称" />
        </el-form-item>
        <el-form-item label="旺旺名" prop="wangName">
          <el-input v-model="form.wangName" placeholder="请输入旺旺名" />
        </el-form-item>
        <el-form-item label="店铺号" prop="storeName">
            <el-select v-model="form.storeName" placeholder="请输入店铺名称">
            <el-option
              v-for="dict in dict.type.store"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="订单图片" prop="psorderPicture">
          <el-upload :action="psorderPictureUploadUrl" :headers="uploadHeaders"
            :on-success="handlePsorderPictureSuccess" :on-remove="handlePsorderPictureRemove"
            :before-upload="beforePsorderPictureUpload" :file-list="psorderPictureFileList" list-type="picture-card"
            :on-preview="handlePicturePreview" :on-error="handlePictureError" :limit="3"
            :on-exceed="handlePictureExceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="订单价格" prop="psorderAmount">
          <el-input v-model="form.psorderAmount" placeholder="请输入订单价格" />
        </el-form-item>
        <el-form-item label="订单状态" prop="psorderState">
          <el-select v-model="form.psorderState" placeholder="请选择订单状态">
            <el-option v-for="item in psorderStateOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抢单类型" prop="psorderSort">
          <el-select v-model="form.psorderSort" placeholder="请选择抢单类型">
            <el-option v-for="item in psorderSortOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="抢单人" prop="acceptedProgrammerId">
          <el-select v-model="form.acceptedProgrammerId" placeholder="请选择抢单人" filterable>
            <el-option v-for="item in acceptedProgrammerUserOptions" :key="item.value" :label="item.label"
              :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- PS订单提现申请对话框 -->
    <el-dialog :title="title" :visible.sync="openWithdrawalDialog" width="500px" append-to-body>
      <el-form ref="withdrawalFormRef" :model="withdrawalForm" :rules="withdrawalRules" label-width="120px">
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model="withdrawalForm.amount" placeholder="请输入提现金额" type="number" step="0.01">
            <template slot="prepend">￥</template>
          </el-input>
        </el-form-item>
        <el-form-item label="凭证图片" prop="imageUrl">
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="handleWithdrawalFileUpload"
            :on-success="handleWithdrawalFileSuccess"
            :on-remove="handleWithdrawalFileRemove"
            :file-list="withdrawalPictureFileList"
            :limit="3"
            accept=".jpg,.jpeg,.png"
            list-type="picture-card"
            :on-preview="handleWithdrawalPicturePreview"
            :on-exceed="handleWithdrawalPictureExceed"
          >
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">最多上传3张jpg/png文件，每张不超过2MB</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitWithdrawalApply">确 定</el-button>
        <el-button @click="cancelWithdrawalApply">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPsorders, getPsorders, delPsorders, addPsorders, updatePsorders } from "@/api/dashboard/psorders"
import { listUsersByRoleName } from "@/api/system/user"
import { getToken } from "@/utils/auth"
import { saveGradWithdrawal } from "@/api/dashboard/psorders";
import { uploadFile } from "@/api/system/file"; // 新增：导入文件上传函数

export default {
  dicts: ['store'],
  name: "Psorders",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // PS订单表格数据
      psordersList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // PS订单提现申请对话框
      openWithdrawalDialog: false, // 控制提现申请对话框显示
      withdrawalForm: { // 提现申请表单数据
        id: null,
        imageUrl: null,
        amount: null
      },
      withdrawalPictureFileList: [], // 提现申请图片文件列表
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        psorderNo: null,
        wangName: null,
        storeName: null,
        psorderPicture: null,
        psorderAmount: null,
        psorderState: null,
        psorderSort: null,
        acceptedProgrammerId: null,
        createBy: null,
      },
      // 表单参数
      form: {
        id: null,
        psorderNo: null,
        wangName: null,
        storeName: null,
        psorderPicture: null, // 将作为逗号分隔的URL字符串
        psorderAmount: null,
        psorderState: '1', // 默认未开始
        psorderSort: '2', // 默认内部技术
        acceptedProgrammerId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      },
      // 图片上传相关
      psorderPictureUploadUrl: process.env.VUE_APP_BASE_API + "/dashboard/psorders/images/upload", // 假设的图片上传URL
      psorderPictureFileList: [], // el-upload的文件列表
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      // 表单校验
      rules: {
        psorderNo: [
          { required: true, message: "订单名称不能为空", trigger: "blur" }
        ],
        wangName: [
          { required: true, message: "旺旺名不能为空", trigger: "blur" }
        ],
        storeName: [
          { required: true, message: "店铺号不能为空", trigger: "blur" }
        ],
        psorderAmount: [
          { required: true, message: "订单价格不能为空", trigger: "blur" }
        ],
        psorderState: [
          { required: true, message: "订单状态不能为空", trigger: "change" }
        ],
        psorderSort: [
          { required: true, message: "抢单类型不能为空", trigger: "change" }
        ],
        acceptedProgrammerId: [
          { required: true, message: "抢单人ID不能为空", trigger: "change" }
        ],
      },
      // 下拉框选项
      psorderStateOptions: [
        { label: '未开始', value: '1' },
        { label: '已抢', value: '2' },
        { label: '已完成', value: '3' },
        { label: '已打款', value: '4' },
        { label: '已驳回', value: '5' }
      ],
      psorderSortOptions: [
        { label: '外部技术', value: '1' },
        { label: '内部技术', value: '2' }
      ],
      acceptedProgrammerUserOptions: [], // 抢单人下拉框选项
      programmerOriginalUserOptions: [], // 存储所有程序员用户
      companyTechUserOptions: [], // 存储公司技术用户
      outsourcedTechUserOptions: [], // 存储外包技术用户
      // 提现申请表单验证规则
      withdrawalRules: {
        amount: [
          { required: true, message: "提现金额不能为空", trigger: "blur" },
          { pattern: /^\d+(\.\d{1,2})?$/, message: "请输入正确的金额格式", trigger: "blur" }
        ],
        imageUrl: [
          { required: true, message: "请至少上传一张凭证图片", trigger: "change" }
        ]
      },
    }
  },
  created() {
    this.getList()
    this.getUserListsPsorders()
  },
  watch: {
    'form.psorderSort': {
      handler(newVal) {
        this.loadProgrammerOptionsPsorders(newVal);
      },
      immediate: true // 立即执行，确保首次加载时根据默认值加载
    },
  },
  methods: {
    /** 根据字典值获取标签 */
    selectDictLabel(datas, value) {
      if (value === undefined || value === null || value === '') {
        return "";
      }
      const actions = [];
      Object.keys(datas).map((key) => {
        if (datas[key].value == ('' + value)) {
          actions.push(datas[key].label);
          return false;
        }
      })
      return actions.join('');
    },
    /** 查询用户列表 */
    getUserListsPsorders() {
      console.log('=== 开始获取用户列表 ===');
      
      const formatUsers = (users) => {
        console.log('formatUsers 接收到的数据:', users);
        if (!users || !Array.isArray(users)) {
          console.warn('用户数据格式不正确:', users);
          return [];
        }
        const formattedUsers = users.map(user => {
          console.log('格式化用户数据:', user);
          return {
            value: user.userId,
            label: `${user.nickName} - ${user.phonenumber}`,
            name: user.nickName
          };
        });
        console.log('格式化后的用户数组:', formattedUsers);
        return formattedUsers;
      };

      // 添加错误处理和调试信息
      console.log('开始调用 listUsersByRoleName API...');
      Promise.all([
        listUsersByRoleName("公司技术").catch(err => {
          console.error('获取公司技术用户失败:', err);
          return { data: [] };
        }),
        listUsersByRoleName("外包技术").catch(err => {
          console.error('获取外包技术用户失败:', err);
          return { data: [] };
        }),
      ]).then(([companyTechRes, outsourcedTechRes]) => {
        console.log('=== API 响应结果 ===');
        console.log('公司技术用户响应:', companyTechRes);
        console.log('外包技术用户响应:', outsourcedTechRes);
        
        const companyTechUsers = formatUsers(companyTechRes.data);
        const outsourcedTechUsers = formatUsers(outsourcedTechRes.data);
        
        console.log('=== 格式化后的用户数据 ===');
        console.log('格式化后的公司技术用户:', companyTechUsers);
        console.log('格式化后的外包技术用户:', outsourcedTechUsers);
        
        // 分别存储公司技术和外包技术用户
        this.companyTechUserOptions = companyTechUsers;
        this.outsourcedTechUserOptions = outsourcedTechUsers;
        
        // 合并所有用户用于显示
        this.programmerOriginalUserOptions = companyTechUsers.concat(outsourcedTechUsers);
        console.log('=== 合并后的所有程序员用户 ===');
        console.log('合并后的所有程序员用户:', this.programmerOriginalUserOptions);
        console.log('合并后用户总数:', this.programmerOriginalUserOptions.length);
        
        // 初始加载时根据默认的psorderSort筛选程序员
        console.log('开始根据默认抢单类型筛选程序员，默认类型:', this.form.psorderSort);
        this.loadProgrammerOptionsPsorders(this.form.psorderSort);
      }).catch(error => {
        console.error('=== 获取用户列表失败 ===');
        console.error('错误详情:', error);
        this.$modal.msgError('获取用户列表失败，请稍后重试');
      });
    },
    
    /** 根据抢单类型加载程序员选项 */
    loadProgrammerOptionsPsorders(psorderSort) {
      console.log('=== 开始加载程序员选项 ===');
      console.log('抢单类型:', psorderSort, '类型:', typeof psorderSort);
      console.log('公司技术用户列表:', this.companyTechUserOptions);
      console.log('外包技术用户列表:', this.outsourcedTechUserOptions);
      
      // Store the current acceptedProgrammerId to re-apply it if valid
      const currentAcceptedProgrammerId = this.form.acceptedProgrammerId;
      console.log('当前已选择的程序员ID:', currentAcceptedProgrammerId);

      if (psorderSort === '1') { // 外部技术
        console.log('=== 使用外包技术用户 ===');
        this.acceptedProgrammerUserOptions = [...this.outsourcedTechUserOptions];
        console.log('外包技术用户数量:', this.acceptedProgrammerUserOptions.length);
      } else if (psorderSort === '2') { // 内部技术
        console.log('=== 使用公司技术用户 ===');
        this.acceptedProgrammerUserOptions = [...this.companyTechUserOptions];
        console.log('公司技术用户数量:', this.acceptedProgrammerUserOptions.length);
      } else {
        console.log('=== 抢单类型不匹配，清空选项 ===');
        this.acceptedProgrammerUserOptions = [];
      }

      console.log('=== 过滤结果 ===');
      console.log('过滤后的程序员选项:', this.acceptedProgrammerUserOptions);
      console.log('过滤后选项数量:', this.acceptedProgrammerUserOptions.length);

      // If the previously selected programmer is still in the filtered options, keep it.
      // Otherwise, clear the selection to avoid displaying a stale or invalid ID.
      if (currentAcceptedProgrammerId && this.acceptedProgrammerUserOptions.some(user => user.value === currentAcceptedProgrammerId)) {
        console.log('保持当前选择的程序员ID:', currentAcceptedProgrammerId);
        this.form.acceptedProgrammerId = currentAcceptedProgrammerId;
      } else {
        console.log('清空程序员选择');
        this.form.acceptedProgrammerId = null; // Clear if not found in new options
      }
      
      console.log('=== 最终结果 ===');
      console.log('最终的程序员选项:', this.acceptedProgrammerUserOptions);
      console.log('最终选择的程序员ID:', this.form.acceptedProgrammerId);
    },
    /** 查询PS订单列表 */
    getList() {
      this.loading = true
      listPsorders(this.queryParams).then(response => {
        this.psordersList = response.rows.map(item => {
          // 确保订单状态和抢单类型是字符串，以便el-select和v-if正确匹配
          item.psorderState = String(item.psorderState);
          item.psorderSort = String(item.psorderSort);
          return item;
        })
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        psorderNo: null,
        wangName: null,
        storeName: null,
        psorderPicture: null, // 重置为null
        psorderAmount: null,
        psorderState: '1', // 默认未开始
        psorderSort: '2', // 默认内部技术
        acceptedProgrammerId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.psorderPictureFileList = []; // 清空文件列表
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加PS订单"
      this.loadProgrammerOptionsPsorders(this.form.psorderSort); // 新增时根据默认抢单类型加载程序员
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getPsorders(id).then(response => {
        this.form = response.data
        // 确保psorderState和psorderSort是字符串类型
        this.form.psorderState = String(response.data.psorderState);
        this.form.psorderSort = String(response.data.psorderSort);

        // 处理订单图片
        if (this.form.psorderPicture) {
          this.psorderPictureFileList = this.form.psorderPicture.split(',').map(url => ({
            name: url.substring(url.lastIndexOf('/') + 1), // 从URL中提取文件名
            url: url,
            status: 'success', // 已上传的图片状态为成功
            uid: this.generateUniqueId() // 为每个文件生成一个唯一的UID
          }));
        } else {
          this.psorderPictureFileList = [];
        }
        // loadProgrammerOptionsPsorders 会在 form.psorderSort 的 watch 触发
        this.open = true
        this.title = "修改PS订单"
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('提交前 psorderPictureFileList:', this.psorderPictureFileList);
      console.log('图片url拼接'+this.form.psorderPicture)
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 改进图片URL拼接逻辑
          const imageUrls = [];
          this.psorderPictureFileList.forEach(file => {
            // 优先使用 file.url，这是el-upload更新后的永久URL
            if (file.url) {
              imageUrls.push(file.url);
            // 如果 file.url 仍然是 blob，尝试从 response 中获取永久 URL (作为后备)
            } else if (file.response && file.response.data && file.response.data.url) {
              imageUrls.push(file.response.data.url);
            }
          });

          // 将多图片URL以逗号分隔保存
          this.form.psorderPicture = imageUrls.join(',') || null;
          console.log('提交后 psorderPicture:', this.form.psorderPicture);
                    console.log('图片url拼接'+this.form.psorderPicture)

          if (this.form.id != null) {
            updatePsorders(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPsorders(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除PS订单编号为"' + ids + '"的数据项？').then(function () {
        return delPsorders(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dashboard/psorders/export', {
        ...this.queryParams
      }, `psorders_${new Date().getTime()}.xlsx`)
    },
    /** 图片上传成功处理 */
    handlePsorderPictureSuccess(response, file, fileList) {
      console.log('handlePsorderPictureSuccess - file (el-upload callback):', file);
      console.log('handlePsorderPictureSuccess - fileList (el-upload callback):', fileList);

      if (response.code === 200) {
        // 关键一步：直接更新 el-upload 回调中的文件对象的 url 和 name 属性
        file.url = response.url; // 将 blob URL 替换为永久 URL，直接从 response 获取 url
        file.name = response.fileName || file.name; // 更新文件名，直接从 response 获取 fileName
        file.status = 'success'; // 确保状态为成功

        // 重新赋值整个 fileList 数组，以触发 Vue 的响应式更新
        this.psorderPictureFileList = [...fileList];

        this.$modal.msgSuccess("图片上传成功");
      } else {
        this.$modal.msgError(response.msg || "图片上传失败，请稍后再试");
        // 如果上传失败，从列表中移除该文件
        this.psorderPictureFileList = fileList.filter(f => f.uid !== file.uid); // 使用过滤确保移除失败的文件
      }
      console.log('handlePsorderPictureSuccess - updated psorderPictureFileList:', this.psorderPictureFileList);
    },
    /** 图片移除处理 */
    handlePsorderPictureRemove(file, fileList) {
      // 从我们的数据属性中过滤掉移除的文件
      this.psorderPictureFileList = this.psorderPictureFileList.filter(f => f.uid !== file.uid);
    },
    /** 图片上传前校验 */
    beforePsorderPictureUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2; // 限制图片大小2MB
      const isJPGPNG = file.type === 'image/jpeg' || file.type === 'image/png';

      if (!isJPGPNG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2 MB!');
      }
      return isJPGPNG && isLt2M;
    },
    /** 图片预览 */
    handlePicturePreview(file) {
      // 确保文件有 URL 才能预览
      if (file.url) {
        this.$preview.open(file.url, file.name || '图片');
      } else {
        this.$message.warning('图片URL无效，无法预览。');
      }
    },
    /** 图片上传失败 */
    handlePictureError(err, file, fileList) {
      this.$message.error('图片上传失败！');
      // 移除上传失败的文件
      this.psorderPictureFileList = this.psorderPictureFileList.filter(f => f.uid !== file.uid);
    },
    /** 图片超出限制 */
    handlePictureExceed(files, fileList) {
      this.$message.warning(`最多只能上传 3 张图片！`);
    },
    /** 订单状态变更处理 */
    handleOrderStatusChange(newVal, row) {
      const id = row.id;
      if (id) {
        updatePsorders({
          id: id,
          psorderState: newVal
        }).then(response => {
          this.$modal.msgSuccess("订单状态更新成功");
          this.getList(); // 刷新列表
        }).catch(error => {
          this.$modal.msgError("订单状态更新失败");
          row.psorderState = row.psorderState; // 恢复原始状态
        });
      }
    },
    /** 提现申请操作 */
    handleWithdrawalApply(row) {
      this.withdrawalForm.id = row.id; // 设置提现申请的订单ID
      this.openWithdrawalDialog = true; // 打开提现申请对话框
    },
    /** PS订单提现申请：文件上传处理 */
    handleWithdrawalFileUpload(param) {
      const formData = new FormData();
      formData.append("file", param.file);
      uploadFile(formData).then(response => {
        if (response.code === 200) {
          // 成功上传后，el-upload 会自动调用 onSuccess 回调
          param.onSuccess(response, param.file); // 告知 el-upload 成功
        } else {
          this.$modal.msgError(response.msg || "凭证图片上传失败");
          param.onError(new Error(response.msg || "上传失败"), param.file);
        }
      }).catch((error) => {
        this.$modal.msgError("凭证图片上传失败，请稍后再试");
        param.onError(error, param.file);
      });
    },
    /** PS订单提现申请：文件上传成功 */
    handleWithdrawalFileSuccess(response, file, fileList) {
      console.log('提现申请图片上传成功 - response:', response);
      console.log('提现申请图片上传成功 - file:', file);
      console.log('提现申请图片上传成功 - fileList:', fileList);
      
      if (response.code === 200) {
        // 更新当前上传文件的URL
        file.url = response.data.url;
        file.name = response.fileName || file.name;
        file.status = 'success';
        
        // 更新文件列表
        this.withdrawalPictureFileList = [...fileList];
        
        // 收集所有已上传成功的图片URL，以逗号分割
        const imageUrls = [];
        this.withdrawalPictureFileList.forEach(uploadFile => {
          if (uploadFile.url && uploadFile.status === 'success') {
            imageUrls.push(uploadFile.url);
          }
        });
        
        // 将多张图片URL以逗号分隔保存
        this.withdrawalForm.imageUrl = imageUrls.join(',');
        console.log('提现申请更新后的imageUrl:', this.withdrawalForm.imageUrl);
        
        this.$modal.msgSuccess("凭证图片上传成功");
      } else {
        this.$modal.msgError(response.msg || "凭证图片上传失败");
        // 上传失败时从列表中移除该文件
        this.withdrawalPictureFileList = fileList.filter(f => f.uid !== file.uid);
      }
    },
    /** 提现申请文件移除 */
    handleWithdrawalFileRemove(file, fileList) {
      console.log('提现申请图片移除 - file:', file);
      console.log('提现申请图片移除 - fileList:', fileList);
      
      // 更新文件列表
      this.withdrawalPictureFileList = fileList.filter(f => f.uid !== file.uid);
      
      // 重新收集所有剩余的图片URL
      const imageUrls = [];
      this.withdrawalPictureFileList.forEach(uploadFile => {
        if (uploadFile.url && uploadFile.status === 'success') {
          imageUrls.push(uploadFile.url);
        }
      });
      
      // 更新imageUrl，如果没有图片则设为null
      this.withdrawalForm.imageUrl = imageUrls.length > 0 ? imageUrls.join(',') : null;
      console.log('提现申请移除后的imageUrl:', this.withdrawalForm.imageUrl);
    },
    /** 提现申请凭证图片预览 */
    handleWithdrawalPicturePreview(file) {
      if (file.url) {
        this.$preview.open(file.url, file.name || '凭证图片');
      } else {
        this.$message.warning('图片URL无效，无法预览。');
      }
    },
    /** 提现申请凭证图片超出限制 */
    handleWithdrawalPictureExceed(files, fileList) {
      this.$message.warning(`最多只能上传 3 张凭证图片！`);
    },
    /** 提交PS订单提现申请 */
    submitWithdrawalApply() {
      this.$refs["withdrawalFormRef"].validate(valid => {
        if (valid) {
          this.$modal.confirm('是否确认对订单号为"' + this.psordersList.find(item => item.id === this.withdrawalForm.id)?.psorderNo + '"的订单发起提现申请？').then(() => {
            return saveGradWithdrawal(this.withdrawalForm); // 调用修改后的接口
          }).then(() => {
            this.$modal.msgSuccess("提现申请提交成功");
            this.openWithdrawalDialog = false;
            this.getList(); // 刷新列表
          }).catch(error => {
            this.$modal.msgError("提现申请提交失败！");
          });
        }
      });
    },
    /** 取消提现申请 */
    cancelWithdrawalApply() {
      this.openWithdrawalDialog = false;
      this.withdrawalForm = {
        id: null,
        imageUrl: null,
        amount: null
      };
      this.withdrawalPictureFileList = [];
      // 重置表单验证状态
      this.$refs["withdrawalFormRef"] && this.$refs["withdrawalFormRef"].resetFields();
    },
    // 辅助函数，用于生成唯一的 uid
    generateUniqueId() {
      return Date.now() + '-' + Math.random().toString(36).substr(2, 9);
    }
  }
}
</script>
